﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using WeiBeeCommon.Core;
using System.ComponentModel;
using System.Xml;
using Microsoft.Win32;

namespace QunFaExpert
{
    /// <summary>
    /// Interaction logic for ManageWeiBee.xaml
    /// </summary>
    public partial class ManageWeiBee : Window
    {
        public ManageWeiBee()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            entities = entityHelper.LoadEntities();
            DecideStartEntity();
        }

        private EntityHelper entityHelper = new EntityHelper();
        private List<Account> adding;
        private List<AuthEntity> entities;
        private int currentEntity;
        private int currentAdding;
        private WeiBeeType selectedType;
        BackgroundWorker bgwAddWeiBee;
        private void btAuth_Click(object sender, RoutedEventArgs e)
        {
            WeiBeeTypeSelector typeselector = new WeiBeeTypeSelector();
            if (!typeselector.ShowDialog().Value)
            {
                return;
            }
            selectedType = typeselector.SelectedType;
            if ((adding == null) || (adding.Count == 0))
            {
                MessageBox.Show("没有新账号需要添加");
                return;
            }
            DecideStartEntity();
            bgwAddWeiBee = new BackgroundWorker();
            bgwAddWeiBee.DoWork += BgwAddWeiBee_DoWork;
            bgwAddWeiBee.RunWorkerCompleted += BgwAddWeiBee_Completed;
            bgwAddWeiBee.RunWorkerAsync();
        }

        private void DecideStartEntity()
        {
            if (entities == null) return;
            currentEntity = 0;
            this.tbPass.Text = string.Empty;
            while ( (currentEntity < entities.Count) && (!string.IsNullOrEmpty(entities[currentEntity].Token)) )
            {
                this.tbPass.Text += "@" + entities[currentEntity].DisplayName + Environment.NewLine;
                currentEntity++;
            }
        }

        private void ShowEntities()
        {
            if (entities == null) return;
            this.tbPass.Text = string.Empty;
            foreach (var entity in entities)
            {
                this.tbPass.Text += "@" + entity.DisplayName + Environment.NewLine;
            }
        }

        private int accountlimit = 1000;
        void BgwAddWeiBee_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((currentAdding < adding.Count) && (entities.Count < accountlimit))
            {
                bgwAddWeiBee.RunWorkerAsync();
            }
            if ( (currentAdding == adding.Count) || (entities.Count==accountlimit))
            {
                ShowEntities();
                MessageBox.Show(string.Format("添加了{0}个新账号.", currentAdding));
                adding = null;
            }
        }

        void BgwAddWeiBee_DoWork(object sender, DoWorkEventArgs e)
        {
            if (currentAdding >= adding.Count) return;
            var oAuth = OAuthFactory.CreateOAuthByWeiBeeType(selectedType);
            try
            {
                oAuth.XAuthLogin(adding[currentAdding].username, adding[currentAdding].pwd);
                if (currentEntity == entities.Count)
                {
                    entities.Add(new AuthEntity());
                }
                entities[currentEntity].ConsumerKey = oAuth.ConsumerKey;
                entities[currentEntity].ConsumerSecret = oAuth.ConsumerSecret;
                entities[currentEntity].Token = oAuth.Token;
                entities[currentEntity].TokenSecret = oAuth.TokenSecret;
                var weibee = WeiBeeFactory.CreateWeiBeeByType(selectedType);// new WeiBeeSina();
                weibee.GetOAuth().ConsumerKey = oAuth.ConsumerKey;
                weibee.GetOAuth().ConsumerSecret = oAuth.ConsumerSecret;
                weibee.SetOAuth(oAuth.Token, oAuth.TokenSecret);
                //weibee.OAuth = oAuth as OAuthSina;
                entities[currentEntity].ActTime = new DateTime(2000, 1, 1);
                entities[currentEntity].user = weibee.GetWeiBeeUser();
                entities[currentEntity].UserType = selectedType;
                entities = entities.Distinct(new AuthEntityComparer()).ToList();
                entityHelper.SaveEntities(entities);
                currentEntity = entities.Count;
            }
            catch(Exception ex)
            {
                MessageBox.Show(string.Format("用户:{0},授权失败,原因{1}", adding[currentAdding].username,ex.Message));
            }
            currentAdding++;
        }

        BackgroundWorker bgwVerifyWeiBeeUser = new BackgroundWorker();
        private void btCheck_Click(object sender, RoutedEventArgs e)
        {
            bgwVerifyWeiBeeUser.DoWork += BgwVerifyWeiBeeUser_DoWork;
            bgwVerifyWeiBeeUser.RunWorkerCompleted += BgwVerifyWeiBeeUser_RunWorkerCompleted;
            bgwVerifyWeiBeeUser.RunWorkerAsync();
        }

        void BgwVerifyWeiBeeUser_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tbFailed.Text = string.Empty;
            var failList = entities.Where(en => notVerifiedTokenList.Contains(en.Token)).ToList();
            foreach (var en in failList)
            {
                tbFailed.Text += "@" + en.DisplayName + Environment.NewLine;
            }
            MessageBox.Show(string.Format("检查完毕，共有{0}授权失败", failList.Count));
        }

        List<string> notVerifiedTokenList = new List<string>();
        void BgwVerifyWeiBeeUser_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (var entity in entities)
            {
                var weibee = WeiBeeFactory.CreateWeiBeeByType(entity.UserType);
                weibee.GetOAuth().ConsumerKey = entity.ConsumerKey;
                weibee.GetOAuth().ConsumerSecret = entity.ConsumerSecret;
                weibee.SetOAuth( entity.Token, entity.TokenSecret);
                try
                {
                    weibee.GetWeiBeeUser();
                }
                catch
                {
                    notVerifiedTokenList.Add(weibee.GetOAuth().Token);
                }
            }
            notVerifiedTokenList = notVerifiedTokenList.Distinct().ToList();
        }

        private void btRemove_Click(object sender, RoutedEventArgs e)
        {
            int count = entities.RemoveAll(en => notVerifiedTokenList.Contains(en.Token));
            entityHelper.SaveEntities(entities);
            MessageBox.Show(string.Format("移除{0}个授权失败账号", count));
        }

        private void btImport_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            bool? file = openDlg.ShowDialog();
            if (file.HasValue && file.Value)
            {
                try
                {
                    adding = Accounts.ReadAccounts(openDlg.FileName);
                    MessageBox.Show(string.Format("账号导入成功，一共导入{0}个账号", adding.Count));
                }
                catch
                {
                    MessageBox.Show("账号从文件导入失败，请检查文件格式");
                }
            }
        }
    }
}
